//
//  ViewController.m
//  KVODemo
//
//  Created by UniHan_iMac on 17/3/28.
//  Copyright © 2017年 UniHan_iMac. All rights reserved.
//

#import "ViewController.h"
#import "People.h"

@interface ViewController ()
{
    People *_people;
}
@end
// KVO 观测属性值的变化。
// KVO 当一个类的对象被释放的时候，需移除观测。
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _people = [[People alloc] init];
    _people.age = 0;
    [_people addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:@"观测年龄的变化"];
}

- (IBAction)Change:(id)sender {
    _people.age ++;
    [_ageButton setTitle:[NSString stringWithFormat:@"%d",_people.age] forState:UIControlStateNormal];
}
// KVO 实现观测的方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    NSLog(@"keyPath=%@",keyPath);
    NSLog(@"object=%@",object);
    NSLog(@"change=%@",change);
    NSLog(@"context=%@",context);
}
// 移除观测
- (void)dealloc{
    [_people removeObserver:self forKeyPath:@"age"];
}
@end




